// 在 store 中创建一个模块（WebSocket 模块）
import { Notification } from 'element-ui';

const state = {
  ws: null, // WebwSocket 实例本体
  proactivelyClose: false, // 是为主动关闭
  heartCheckTimer: null, // 心跳定时器
};

const mutations = {
  SET_ws (state, ws) {
    state.ws = ws;
    console.log("SET_ws", state.ws);
  },
  CLEAR_ws (state) {
    state.ws = null;
  },
  SET_proactivelyClose (state, data) {
    state.proactivelyClose = data
  },
  SET_heartCheckTimer (state, timer) {
    state.heartCheckTimer = timer;
  },
};

const actions = {
  startWebSocket ({ commit, dispatch, state }) {
    if (state.ws) return
    console.log("SOCKET_PATH:", process.env);
    // ws:// + 请求接口
    const socketUrl = 'ws://127.0.0.1:3000';
    const webSocketServer = new WebSocket(socketUrl);

    webSocketServer.onopen = () => {
      console.log(`${new Date().toLocaleString()} >>>>> 连接成功`, webSocketServer);
      Notification({
        type: "success",
        title: '成功',
        message: '会话连接成功',
        position: "top-right",
        duration: 3000,
        showClose: true
      });
      // 保存 WebSocket 连接信息
      commit('SET_ws', webSocketServer);
      // // 在这里调用 sendWebSocketMessage，确保 state.ws 已经被正确设置
      // 开始心跳检测
      dispatch('startHeartCheck');
    };

    webSocketServer.onmessage = (e) => {
      console.log(`${new Date().toLocaleString()} >>>>> 收到消息 ${e.data}`, state.ws);
      if (e.data !== "pong") {
        Notification({
          type: "success",
          title: '新消息',
          message: e.data,
          position: "top-right",
          duration: 3000,
          showClose: true
        });
      }
    };

    webSocketServer.onclose = () => {
      console.log(`${new Date().toLocaleString()} >>>>> 连接已关闭`);
      // 尝试重新连接 - 前提是非主动关闭
      if (!state.proactivelyClose) dispatch('reconnectWebSocket');
    };

    webSocketServer.onerror = (e) => {
      console.log(`${new Date().toLocaleString()} >>>>> 数据传输发生异常`, e);
      Notification({
        type: "error",
        title: '错误',
        message: '会话连接异常，服务已断开',
        position: "top-right",
        duration: 3000,
        showClose: true
      });
    };
  },

  sendWebSocketMessage ({ state }, msg) {
    console.log(`${new Date().toLocaleString()} >>>>> 发送消息：${msg}`, state.ws);
    state.ws.send(msg);
  },

  reconnectWebSocket ({ dispatch }) {
    // 尝试主动重连时，不弹出消息
    dispatch('clearWebSocket', false);
    // 递归调用，一直尝试重连
    setTimeout(() => {
      dispatch('startWebSocket');
    }, 6000);
  },

  clearWebSocket ({ commit, dispatch, state }, payload) {
    if (state.ws && payload) {
      Notification({
        type: "success",
        title: '已关闭连接',
        message: '成功！',
        position: "top-right",
        duration: 3000,
        showClose: true
      });
      state.ws.close();
      
      
      commit('CLEAR_ws');
      commit('SET_proactivelyClose', payload ? true : false)
      // 关闭心跳监测
      dispatch('clearHeartCheckTimer');
    }
  },

  startHeartCheck ({ commit, dispatch, state }) {
    console.log(`${new Date().toLocaleString()} >>>>> 开始心跳检测`, state.ws);
    // 清除之前的计时器
    dispatch('clearHeartCheckTimer');

    // 创建新的计时器
    dispatch('sendWebSocketMessage', 'ping');
    const timer = setInterval(() => {
      if (!state.ws || state.ws.readyState !== WebSocket.OPEN) {
        console.log(`${new Date().toLocaleString()} >>>>> 心跳检测失败,触发重连`, state.ws);
        dispatch('reconnectWebSocket');
      } else {
        console.log(`${new Date().toLocaleString()} >>>>> 心跳正常,继续下一次心跳检测`, state.ws);
        dispatch('sendWebSocketMessage', 'ping');
      }
    }, 1000 * 29);
    commit('SET_heartCheckTimer', timer);
  },

  clearHeartCheckTimer ({ commit, state }) {
    const timer = state.heartCheckTimer;
    timer && clearInterval(timer);
    commit('SET_heartCheckTimer', null);
  },
};

export default {
  state,
  mutations,
  actions,
};
